package sd.settemmezzo.register;

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Vector;

import sd.settemmezzo.common.PlayerInterface;
import sd.settemmezzo.common.Registration;

public class RegistrationServer extends UnicastRemoteObject implements Registration {
	
	private static final long serialVersionUID = 7745840583791622565L;
	
	private Vector<PlayerInterface> players;
	private final int MINPLAYERS = 3;
	private final int MAXPLAYERS = 12;
	private int idCounter = 1;
	
	public RegistrationServer() throws RemoteException {
		super();
		players = new Vector<PlayerInterface>();
	}

	public int register(PlayerInterface player) throws RemoteException {
		player.setId(idCounter);
		players.add(player);
		System.out.println("[register] Registred Player: name='" + 
				player.getName() + "', host='" + player.getIp() + "'");
		
		if (players.size() >= MINPLAYERS) {
			Registry registry = LocateRegistry.getRegistry();
			for (PlayerInterface p : players) {
				try {
		            PlayerInterface client = (PlayerInterface) registry.lookup(p.getName());
		            client.setPlayersList(players);
		            System.out.println("Send Vector<Player> to node " + p.getName() + " (" + p.getIp() + ")");
				} catch (Exception e) {
		            System.err.println("[RegistrationServer] exception looking up client:");
		            e.printStackTrace();
		        }
			}
		}
		
		idCounter++;
		return player.getId();
	}

	public boolean unregister(String name) throws RemoteException {
		// TODO Auto-generated method stub
		return false;
	}
	
	public static void main(String[] args) {
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }
        
        String name = "//localhost/Registration";
        try {
            Registration registration = new RegistrationServer();
            Naming.rebind(name, registration);
            System.out.println("[RegistrationServer] Bound.");
        } catch (Exception e) {
            System.err.println("RegistrationServer exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
